package com.sxz.mall.mallsearch.thread;

import java.util.concurrent.*;

/**
 * completableFuture, 传入Runnable和executor，相当于使用线程池执行任务
 */
public class CompletableFutureDemo {
    // 自定义执行器
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            100,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main线程开始了11.....");

        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            System.out.println("线程开始了.....");
            int i = 100 / 50;
//            return i;
        }, executor);

        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("线程开始了11.....");
            int i = 100 / 50;
            System.out.println("线程结束了11.....");
            return i;
        }, executor);

        // 两个任务都完成后执行
        // runAfterBoth： 无法获取结果和返回，    等两个执行完了再执行   如果添加了 Async 就添加executor
        // thenAcceptBoth  可以获取到两个的结果， 多个值...args
        // thenCombine    可以获取和返回
        CompletableFuture<Void> future = future1.runAfterBoth(future2, () -> {
            System.out.println("任务3执行");
        });


        // 两个任务完成一个就执行
        // runAfterEither
        // acceptEither
        // applyToEither

        // allOf  anyOf

        System.out.println("获取的线程结果....." + future1.get());

        CompletableFuture<Void> future3 = CompletableFuture.allOf(future, future1, future2);
        CompletableFuture<Object> future4 = CompletableFuture.anyOf(future, future1, future2);


        System.out.println("main线程结束了11.....");

    }
}
